<template>
  <div class="container">
    <div class="button-bar">
      <span class="condition">
        <el-icon v-if="condition !== undefined && condition.length > 0">
          <Search />
        </el-icon>
        <el-tag v-for="(item, index) in condition" :key="index" closable effect="dark" @close="handleTagClose(index)">
          {{ item.name }}：{{ item.label }}
        </el-tag>
      </span>
      <span class="buttons">
        <el-button v-for="(item, index) in tableConfig.buttons" :key="index" type="primary" plain size="default"
          @click="click(item.click, item)" :icon="item.icon">
          {{ item.name }}
        </el-button>
        <el-button v-if="tableConfig.selectColumn" type="primary" plain size="default" icon="Setting"
          @click="openDrawer()">选择列</el-button>
      </span>
    </div>

    <el-table size="default" style="width: 100%" v-loading="tableLoading" :data="tableData" fit highlight-current-row
      @selection-change="handleSelectionChange" :height="tableHeight"
      :header-cell-style="{ background: '#F3F5F7', textAlign: 'center', color: '#333333', padding: '4px 0px 4px 0px' }"
      :cell-style="{ padding: '5px 0px 5px 0px' }">
      <el-table-column v-if="tableConfig.multiSelection === '1'" type="selection" width="30" align="center">
      </el-table-column>
      <el-table-column v-if="tableConfig.ifIndex === '1'" label="序号" width="60" align="center" type="index" :index="
        (index) => {
          return index + 1 + page.rowFrom
        }
      ">
      </el-table-column>
      <el-table-column
        v-for="(columnItem, index) in tableConfig.columnData.filter((item) => { return item.visible == '1' })"
        :align="columnItem.align" :width="columnItem.width" :min-width="columnItem.min_width" :key="index"
        :fixed="columnItem.fixed" show-overflow-tooltip>
        <template #header>
          {{ columnItem.name }}
          <table-header-popover v-if="columnItem.is_condition" :columnType="columnItem.query_column_type"
            :columnCode="columnItem.code" :columnValue="condition[columnItem.code]" :dataUrl="columnItem.data_url"
            @search="changeCondition" />
          <table-header-sort v-if="columnItem.sort" :columnCode="columnItem.code" @changeSort="changeSort" />
        </template>
        <template #default="scope">
          <!--链接-->
          <span v-if="columnItem.click !== undefined && columnItem.click.length >= 1">
            <!--链接+图片-->
            <el-image v-if="columnItem.image_code != undefined" style="width: 32px; height: 32px"
              :src="scope.row[columnItem.image_code]" fit="contain" />
            <el-link type="primary" @click="click(columnItem.click, scope.row, columnItem.link_url)">{{
                scope.row[columnItem.code]
            }}
            </el-link>
          </span>
          <!--图片-->
          <span v-else-if="columnItem.table_column_type == 'image'">
            <el-image style="width: 32px; height: 32px" :src="scope.row[columnItem.code]" fit="contain" />
          </span>
          <!--按钮-->
          <!--选项-->
          <span v-else-if="columnItem.options !== undefined">
            {{ transcode(columnItem.options, scope.row[columnItem.code]) }}
          </span>
          <!--文字-->
          <span v-else>
            <!--文字+图标-->
            <component v-if="columnItem.icons !== undefined" :is="columnItem.icons[scope.row[columnItem.icon_code]]"
              style="width:16px; height:16px;" />
            <!--文字+图片-->
            <el-image v-if="columnItem.image_code != undefined" style="width: 32px; height: 32px"
              :src="scope.row[columnItem.image_code]" fit="contain" />
            <!--显示转码-->
            <template v-if="columnItem.show_code !== undefined">{{ scope.row[columnItem.show_code] }}</template>
            <!--文字-->
            <template v-else>{{ scope.row[columnItem.code] }}</template>
          </span>
        </template>
      </el-table-column>

      <el-table-column v-if="tableConfig.operations !== null && tableConfig.operations.length > 0" label="操作"
        :width="tableConfig.operationWidth" fixed="right">
        <template #default="scope">
          <el-link
            v-for="(buttonItem, index) in tableConfig.operations.filter((item) => { return item.is_more == '0' })"
            :key="index" :type="buttonItem.type !== null ? buttonItem.type : 'primary'"
            @click="click(buttonItem.click, scope.row, buttonItem.link_url)">
            <!-- 根据条件是否显示 -->
            <slot v-if="buttonItem.show_by_code !== null">
              <slot v-if="scope.row[[buttonItem.show_by_code]] === buttonItem.when_value">
                <component v-if="buttonItem.icon !== null" :is="buttonItem.icon" style="width:16px; height:16px;" />
                {{ buttonItem.name }}
              </slot>
            </slot>
            <!-- 显示按钮 -->
            <slot v-else-if="buttonItem.name !== null">
              <component v-if="buttonItem.icon !== null" :is="buttonItem.icon" style="width:16px; height:16px;" />
              {{ buttonItem.name }}
            </slot>
            <!-- 动态按钮名称 -->
            <slot v-else-if="buttonItem.name_by_option !== null">
              <component :is="buttonItem.icons[scope.row[buttonItem.name_by_option]]"
                style="width:16px; height:16px;" />
              {{ buttonItem.options[scope.row[buttonItem.name_by_option]] }}
            </slot>
          </el-link>
          <!-- 下拉菜单 -->
          <el-dropdown v-if="tableConfig.operations.filter((item) => { return item.is_more == '1' }).length > 0"
            @command="handleCommand">
            <span class="el-dropdown-link">更多…</span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                  v-for="(item, index) in tableConfig.operations.filter((item) => { return item.is_more == '1' })"
                  :key="index" :icon="item.icon"
                  :command="{ event: item.click, item: scope.row, link_url: item.link_url }">
                  {{ item.name }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination v-if="tableConfig.ifPage" v-model:currentPage="page.pangeNo" v-model:page-size="page.pageSize"
      :page-sizes="[10, 15, 20, 30, 50]" layout="total, sizes, prev, pager, next, jumper" :total="page.rowCount"
      @current-change="changePage" @size-change="changePage" />

    <el-drawer v-model="drawerVisible" title="选择字段" append-to-body>
      <el-table :data="tableConfig.columnData" :row-style="{ cursor: 'move' }" row-key="code">
        <el-table-column label="选择" width="80" align="center">
          <template #default="scope">
            <el-checkbox v-model="scope.row.visible" true-label="1" false-label="0" size="large"
              :disabled="scope.row.fixedColumn == '1'" />
          </template>
        </el-table-column>
        <el-table-column label="列名" prop="name" align="left"> </el-table-column>
      </el-table>
    </el-drawer>

  </div>

</template>
<script setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, onMounted } from "vue"
import { useRouter } from "vue-router"
import Sortable from 'sortablejs'

import tableHeaderSort from "../TableHeader/sort.vue"
import tableHeaderPopover from "../TableHeader/popover.vue"
import request from "@/utils/axios"

const props = defineProps({
  tableConfig: Object
})
const emits = defineEmits(['add', 'del', 'edit', 'event1', 'event2', 'event3', 'event4', 'event5', 'event6', 'event7', 'event8', 'event9', 'event10'])

const tableData = ref([])  //表格数据
const tableLoading = ref() //加载中状态
const tableHeight = ref() //表格高度
const page = ref({ rowCount: 0, pageSize: 20, pageNo: 1, rowFrom: 0 }) //列表分页
const orderArr = ref([])  //排序条件
const selectedRow = ref([])  //选中行
const condition = ref([]) //查询条件
const drawerVisible = ref(false) //抽屉是否可见

onMounted(() => {
  console.log("table mounted:", props.tableConfig)
  if (props.tableConfig.dataUrl) { loadData() }
  if (props.tableConfig.autosize === '1') { autosize() }
})
// 自动高度
const autosize = () => {
  let height = 80
  if (props.tableConfig.heightMinus) {
    height = height + Number(props.tableConfig.heightMinus)
  }
  tableHeight.value = window.innerHeight - height

  window.onresize = () => {
    tableHeight.value = window.innerHeight - height
  }
}

// 加载数据
const loadData = () => {
  //console.log(props.tableConfig.dataUrl)  
  tableLoading.value = true
  request({
    url: props.tableConfig.dataUrl,
    method: "post",
    data: {
      condition: condition.value,
      sort: orderArr.value,
      page: page.value
    }
  }).then((res) => {
    //console.log(res.data)
    tableData.value = res.data.ds1
    if (res.data.ds1page) {
      page.value = res.data.ds1page
    }
    tableLoading.value = false
  }).catch((err) => {
    //console.log(err)
    ElMessage({ showClose: true, message: '网络错误，请稍后再试。', type: 'error', duration: 5000 })
    tableLoading.value = false
  })
}
defineExpose({ loadData })
// 划出右侧抽屉
const openDrawer = () => {
  drawerVisible.value = true
  setTimeout(() => {
    rowDrop()
  }, 1000)
}
//行拖拽
const rowDrop = () => {
  const tbody = document.querySelector(".el-drawer__body .el-table__body-wrapper tbody")
  Sortable.create(tbody, {
    onEnd({ newIndex, oldIndex }) {
      console.log(newIndex, oldIndex)

      const currRow = props.tableConfig.columnData.splice(oldIndex, 1)[0]
      props.tableConfig.columnData.splice(newIndex, 0, currRow)
    },
  })
}
// 点击触发方法: go打开窗口，其他执行父组件方法add,del,edit,event1...10
const click = (method, item, link_url) => {
  if (method == 'go') {
    go(link_url, item)
  } else {
    emits(method, item)
  }
}
// 跳转 "/design/form?code=member&id=id"
const go = (link_url, item) => {
  //console.log("url", link_url, item)
  let arr_url = link_url.split('?')
  if (arr_url.length == 1) {
    openWin(arr_url[0])
  } else {
    let arr_arg = arr_url[1].split('&')
    //console.log(arr_arg)
    let args = {}
    for (let arg of arr_arg) {
      let arr_pair = arg.split('=')
      //console.log(arr_pair)
      args[arr_pair[0]] = item[arr_pair[1]]
    }
    //console.log(args)
    openWinWithParam(arr_url[0], args)
  }
}
const router = useRouter()
// 打开窗口
const openWin = (url) => {
  const { href } = router.resolve({
    path: url
  })
  window.open(href, '_blank')
}
const openWinWithParam = (url, args) => {
  const { href } = router.resolve({
    path: url,
    query: args
  })
  window.open(href, '_blank')
}
// 下拉菜单，更多操作
const handleCommand = (command) => {
  console.log(command.event, command.item, command.link_url)
}
// 表格选择行
const handleSelectionChange = (val) => {
  selectedRow.value = val
  //console.log(selectedRow.value)
}
// 改变当前页
const changePage = (val) => {
  console.log(val)
  page.value.pageNo = val
  loadData()
}
// 改变查询条件
const changeCondition = (val) => {
  let position = findInArr(condition.value, val.code)
  if (position > -1) {
    condition.value.splice(position, 1)
  }
  //tableConfig.columnData中找name
  val.name = findName(val.code)
  condition.value.push(val)
  console.log(condition.value)
  loadData()
}
const findName = (code) => {
  for (let item of props.tableConfig.columnData) {
    if (item.code == code) {
      return item.name
    }
  }
  return ''
}
// 删除条件
const handleTagClose = (index) => {
  //console.log(index)
  condition.value.splice(index, 1)
  loadData()
}
// 改变排序条件
const changeSort = (code, val) => {
  let position = findInArr(orderArr.value, code)
  //console.log(position)
  if (position > -1) {
    orderArr.value.splice(position, 1)
  }
  if (val != '0') {
    orderArr.value.unshift({ code, val })
  }
  //console.log(orderArr.value)
  loadData()
}
// 查找在数组中的位置
const findInArr = (arr, code) => {
  let i = 0
  for (let item of arr) {
    if (item.code == code) {
      return i
    }
    i++
  }
  return -1
}
// 转码显示
const transcode = (options, value) => {
  for (const item of options) {
    if (item.value === value) {
      return item.label
    }
  }
  return ""
}
</script>
<style lang="scss">
@import "@/styles/dynamicTable";
</style>